<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace Selibra\Event;


use Psr\EventDispatcher\EventDispatcherInterface;
use Selibra\Di\DI;
use Selibra\Di\Exception\NoImplementClass;
use Selibra\Event\Exception\StoppableEventException;
use Selibra\Tools\Console;


/**
 * 事件分发器，负责进行监听者的调用
 * Class EventDispatcher
 * @package Selibra\Event
 */
class EventDispatcher implements EventDispatcherInterface
{

    /**
     * 事件
     * @var object
     */
    private object $event;

    /**
     * @inheritDoc
     */
    public function dispatch(object $event)
    {
        $this->event = $event;
        try {
            $listeners = $this->getListeners();
            foreach ($listeners as $listener) {
                $listener->execute($event);
            }
        } catch (StoppableEventException $exception) {
            // 终止监听
            Console::log($exception);
        } catch (NoImplementClass $exception) {
            Console::log($exception);
        }
    }


    /**
     * @return Listener[]
     * @throws \Selibra\Di\Exception\NoImplementClass
     */
    public function getListeners()
    {
        /** @var ListenerProvider $listenerProvider */
        $listenerProvider = DI::getObjectContext(ListenerProvider::class);
        return $listenerProvider->getListenersForEvent($this->event);
    }

}
